#!/bin/bash
# ndbd   Startup script for the NDBD
# chkconfig: 2 50 22
#

ndbd_bin    = /usr/local/mysql/bin/ndbd
mgmserver   = mgm  # “mgm1,mgm2”

if ! test -x $ndbd_bin; then
    echo "Can't execute $ndbd_bin"
    exit 1
fi

initial() {
    pids=`ps aux | grep -iv "grep" | grep -i "$ndbd_bin" | wc -l`
    if [ $pids -eq 0 ]; then
    	$ndbd_bin -c $mgmserver --initial
    	echo "NDB daemon initial."
    else
    	echo "NDB daemon is already running."
    fi
}

start() {
    pids=`ps aux | grep -iv "grep" | grep -i "$ndbd_bin" | wc -l`
    if [ $pids -eq 0 ]; then
    	$ndbd_bin -c $mgmserver
    	echo "NDB daemon started."
    else
    	echo "NDB daemon is already running."
    fi
}

stop() {
    pids=`ps aux | grep -iv "grep" | grep -i "$ndbd_bin" | wc -l`
    if [ $pids -ne 0 ]; then

        pids=`ps aux | grep -iv "grep" | grep -i "$ndbd_bin" | awk '{ print $2 }'`
    	for pid in $(echo $pids); do
       	    kill $pid 2> /dev/null
    	done

        sleep 3

    	pids=`ps aux | grep -iv "grep" | grep -i "$ndbd_bin" | wc -l`
    	if [ $pids -eq 0 ]; then
            echo "NDB daemon is stopped."
    	else
            echo "Could not stop NDB daemon."
    	fi
    else
    	echo "NDB daemon is not running."
    fi
}

case "$1" in
    start)
    	start
    	;;
    stop)
    	stop
    	;;
    initial)
    	initial
    	;;
    restart)
    	stop
        sleep 3
    	start
    	;;
    *)
    	echo $"Usage: $0 {start|stop|restart|initial}" >&2
    	;;
esac

exit 0
